﻿using SSC.Models;
using SSC.Services;
using SSC.Views;
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Threading;

namespace SSC.ViewModels
{
    internal class MainViewModel : INotifyPropertyChanged
    {
        private string _plcConnectedStatus;
        private readonly MaintenanceService _maintenanceService;
        private Window _ownerWindow;
        private DispatcherTimer _timer;
        public string PlcConnectedStatus
        {
            get { return _plcConnectedStatus; }
            set
            {
                if (_plcConnectedStatus != value)
                {
                    _plcConnectedStatus = value;
                    OnPropertyChanged(nameof(PlcConnectedStatus)); // 通知UI更新
                }
            }
        }

        public string CurrentUserName => Variable.CurrentUserName;
        public string CurrentUserRole => Variable.CurrentUserRole;

        // 实现INotifyPropertyChanged接口
        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        public MainViewModel(Window ownerWindow)
        {
            _maintenanceService = new MaintenanceService();
            _ownerWindow = ownerWindow;
            Variable.OnPlcStatusChanged += OnPlcStatusChanged;
            Variable.OnCurrentUserChanged += (s, e) =>
            {
                OnPropertyChanged(nameof(CurrentUserName));
                OnPropertyChanged(nameof(CurrentUserRole));
            };
            OnPlcStatusChanged(this, Variable.PlcConnectedStatus);
            //每小时检查一次保养是否过期
            _timer = new DispatcherTimer();
            _timer.Interval = TimeSpan.FromHours(1);
            _timer.Tick += (s, e) => GetOverdueItems();
            _timer.Start();
            GetOverdueItems();
        }

        // 当PLC连接状态变化时触发此方法
        private void OnPlcStatusChanged(object sender, bool isConnected)
        {
            PlcConnectedStatus = isConnected ? "PLC连接成功" : "PLC未连接";
        }

        // 在 ViewModel 被销毁时取消订阅事件（防止内存泄漏）
        public void UnsubscribeFromEvents()
        {
            Variable.OnPlcStatusChanged -= OnPlcStatusChanged;
        }

        protected bool SetProperty<T>(ref T field, T newValue, [CallerMemberName] string propertyName = null)
        {
            if (!Equals(field, newValue))
            {
                field = newValue;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
                return true;
            }

            return false;
        }

        private string currentUsername;

        public string CurrentUsername { get => currentUsername; set => SetProperty(ref currentUsername, value); }
        public List<MaintenanceItemModel> GetOverdueItems()
        {
            var items = _maintenanceService.GetAllItems();

            var overdueItems = items
                .Where(item => item.LastMaintainAt.AddDays(item.CycleDays) < DateTime.Now)
                .ToList();

            return overdueItems;
        }
    }
}
